package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.dto.LExamDTO;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LExamController
 * @date 2021.03.25 10:54
 * @describe 考次管理
 */
@Api("考次管理")
@RestController
@RequestMapping("/manager/exam")
public class LExamController extends WebController<LExam> {

    @Autowired
    ILExamService ilExamService;
    @Autowired
    ILExtractQuestionsService ilExtractQuestionsService;
    @Autowired
    ILExamPaperService ilExamPaperService;
    @Autowired
    ILQuestionsService ilQuestionsService;
    @Autowired
    ILQuestionsTypeService ilQuestionsTypeService;
    @Autowired
    ILOrganizationService ilOrganizationService;
    @Autowired
    ILExamSortService ilExamSortService;
    @Autowired
    ILQuestionsSortService ilQuestionsSortService;
    @Autowired
    ILExamTargetService ilExamTargetService;

    //获取考次列表
    @ApiOperation(value = "获取考次列表")
    @UserLoginToken(required = true)
//    @LoginRequired //测试接口 无需登录
    @PostMapping("/list")
    public PageResult<LExam> list(@RequestBody LExamDTO lExamDTO){
        try {
            if (lExamDTO==null||lExamDTO.getPage()==null||lExamDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lExamDTO.getPage(),lExamDTO.getRows());
            QueryWrapper<LExam> queryWrapper = new QueryWrapper<LExam>();
            if(lExamDTO.getExamSortId()!=null)
                queryWrapper.eq("exam_sort_id",lExamDTO.getExamSortId());
            if(lExamDTO.getReleaseState()!=null)
                queryWrapper.eq("release_state",lExamDTO.getReleaseState());
            if(lExamDTO.getExamName()!=null)
                queryWrapper.like("exam_name",lExamDTO.getExamName());
            if(lExamDTO.getOrganizationId()!=null)
                queryWrapper.eq("organization_id",lExamDTO.getOrganizationId());
            if(StringUtils.isNotEmpty(lExamDTO.getType()))
                queryWrapper.eq("type",lExamDTO.getType());
            Page<LExam> lExams = (Page<LExam>) ilExamService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lExams)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LExam lExam: lExams) {
                LOrganization lOrganization = ilOrganizationService.getById(lExam.getOrganizationId());
                if(null != lOrganization)
                    lExam.setOrganizationName(lOrganization.getOrganizationName());
                LExamSort lExamSort = ilExamSortService.getById(lExam.getExamSortId());
                if(null != lExamSort)
                    lExam.setExamSortName(lExamSort.getExamSortName());
                QueryWrapper<LExamTarget> targetQueryWrapper = new QueryWrapper<LExamTarget>();
                targetQueryWrapper.eq("exam_id",lExam.getExamId());
                LExamTarget lExamTarget = ilExamTargetService.getOne(targetQueryWrapper);
                if(null != lExamTarget)
                    lExamTarget.setExamTarget(lOrganization.getOrganizationName());
                lExam.setlExamTarget(lExamTarget);
            }
            // 返回
            return new PageResult(lExams.getTotal(), lExams, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //删除考次
    @ApiOperation(value = "删除考次")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除考次", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LExam lExam){
        try {
            if(lExam!=null){
                if(lExam.getExamId()!=null){
                    QueryWrapper<LExam> queryWrapper = new QueryWrapper<LExam>();
                    queryWrapper.in(true, "exam_id", lExam.getExamId());
                    if(ilExamService.remove(queryWrapper)){
                        // 删除对应的试卷，对应的抽题策略  对应的考试
                        QueryWrapper<LExtractQuestions> lExtractQuestionsQueryWrapper = new QueryWrapper<LExtractQuestions>();
                        lExtractQuestionsQueryWrapper.eq("exam_id",lExam.getExamId());
                        ilExtractQuestionsService.remove(lExtractQuestionsQueryWrapper);
                        QueryWrapper<LExamPaper> lExamPaperQueryWrapper = new QueryWrapper<LExamPaper>();
                        lExamPaperQueryWrapper.eq("exam_id",lExam.getExamId());
                        ilExamPaperService.remove(lExamPaperQueryWrapper);
                        //TODO 需要删除学生开始记录？
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //更新考次
    @ApiOperation(value = "更新考次")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新考次", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LExam lExam, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lExam!=null){
            lExam.setUpdateTime(new Date());
            lExam.setUpdateUser(userId);
            if(ilExamService.updateById(lExam)){
                // 添加分组
                LExamTarget lExamTarget = lExam.getlExamTarget();
                if(null != lExamTarget){
                    if(StringUtils.isNotEmpty(lExamTarget.getExamTargetId())){
                        ilExamTargetService.updateById(lExamTarget);
                    }else{
                        lExamTarget.setExamId(lExam.getExamId());
                        ilExamTargetService.save(lExamTarget);
                    }
                }
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //新增考次
    @ApiOperation(value = "添加考次")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加考次", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LExam lExam, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lExam!=null) {
                if (StringUtils.isEmpty(lExam.getExamCode())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_CODE);
                }
                if (StringUtils.isEmpty(lExam.getExamName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_NAME);
                }
                if (StringUtils.isEmpty(lExam.getOrganizationId())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSE_COMP);
                }
                if (StringUtils.isEmpty(lExam.getExamSortId())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_SORT);
                }
                if (StringUtils.isEmpty(lExam.getExamCoverUrl())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_COVER_URL);
                }
                if (StringUtils.isEmpty(lExam.getFailureTime())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_FAILURE_TIME);
                }
                if (StringUtils.isEmpty(lExam.getTimingType())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_TIMING_TYPE);
                }
                if (StringUtils.isEmpty(lExam.getAchievementType())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_ACHIEVEMENT_TYPE);
                }
                if (StringUtils.isEmpty(lExam.getExamSubmit())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_SUBMIT);
                }
                if (StringUtils.isEmpty(lExam.getExamFrequency())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_FREQUENCY);
                }
                lExam.setCreateUser(userId);
                lExam.setCreateTime(new Date());
                lExam.setReleaseState("0");// 默认为组卷中
                if (ilExamService.save(lExam)) {
                    // 添加分组
                    LExamTarget lExamTarget = lExam.getlExamTarget();
                    if(null != lExamTarget){
                        lExamTarget.setExamId(lExam.getExamId());
                        ilExamTargetService.save(lExamTarget);
                    }
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lExam.getExamId());
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //新增抽题策略
    @ApiOperation(value = "新增抽题策略")
    @PostMapping("/eqadd")
    @UserLoginToken
    @Log(title = "新增抽题策略", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> eqadd(@RequestBody LExam lExam, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lExam!=null) {
                if (StringUtils.isEmpty(lExam.getExamId())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
                }
                // 修改抽题信息
                lExam.setUpdateTime(new Date());
                lExam.setUpdateUser(userId);
                if(ilExamService.updateById(lExam)) {
                    List<LExtractQuestions> lExtractQuestionsList = lExam.getlExtractQuestionsList();
                    for (LExtractQuestions lExtractQuestions : lExtractQuestionsList) {
                        if (StringUtils.isNotEmpty(lExtractQuestions.getExtractQuestionsId()))
                            ilExtractQuestionsService.updateById(lExtractQuestions);
                        else
                            ilExtractQuestionsService.save(lExtractQuestions);
                    }
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //查询抽题策略
    @ApiOperation(value = "查询抽题策略")
    @GetMapping("/eqinfo")
    @UserLoginToken
    public CommonResult<Object> eqinfo(@RequestParam("id")Integer id){
        try {
            QueryWrapper<LExtractQuestions> lExtractQuestionsQueryWrapper = new QueryWrapper<LExtractQuestions>();
            lExtractQuestionsQueryWrapper.eq("exam_id",id);
            List<LExtractQuestions> list = ilExtractQuestionsService.list(lExtractQuestionsQueryWrapper);
            for (LExtractQuestions lExtractQuestions: list) {
                LQuestionsType lQuestionsType = ilQuestionsTypeService.getById(lExtractQuestions.getQuestionsTypeId());
                if(null != lQuestionsType)
                    lQuestionsType.setQuestionsTypeName(lQuestionsType.getQuestionsTypeName());
            }
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //删除
    @ApiOperation(value = "删除抽题策略")
    @PostMapping("/eqdel")
    @UserLoginToken
    @Log(title = "删除抽题策略", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> eqdel(@RequestBody LExtractQuestions lExtractQuestions){
        try {
            if(lExtractQuestions!=null){
                if(lExtractQuestions.getExtractQuestionsId()!=null){
                    QueryWrapper<LExtractQuestions> queryWrapper = new QueryWrapper<LExtractQuestions>();
                    queryWrapper.eq("extract_questions_id", lExtractQuestions.getExtractQuestionsId());
                    if(ilExtractQuestionsService.remove(queryWrapper)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //查询对应题型分类下题的数量
    @ApiOperation(value = "查询对应题型分类下题的数量")
    @GetMapping("/queryNum")
    @UserLoginToken
    public CommonResult<Object> queryNum(@RequestParam("questionsSortId") Integer questionsSortId,
                                         @RequestParam(value = "knowledge",required = false)String knowledge,
                                         @RequestParam(value = "difficulty",required = false)String difficulty){
        try {
            if(StringUtils.isEmpty(questionsSortId))
                return (CommonResult)ResultUtil.error(ResultEnum.NOT_QUESTIONS_SORT);
            QueryWrapper<LQuestions> queryWrapper = new QueryWrapper<LQuestions>();
            queryWrapper.select("questions_type,count(*) as count");
            // 题库分类下所有题 包括子分类
            LQuestionsSort lQuestionsSort = ilQuestionsSortService.getById(questionsSortId);
            List<Integer> ids = new ArrayList<>();
            ids.add(lQuestionsSort.getQuestionsSortId());
            List<Integer> sortIds = nodeStr(ids);
            queryWrapper.in("questions_sort_id",sortIds);
            if(StringUtils.isNotEmpty(knowledge))
                queryWrapper.like("knowledge",knowledge);
            if (StringUtils.isNotEmpty(difficulty))
                queryWrapper.eq("questions_difficulty",difficulty);
            queryWrapper.groupBy("questions_type");
            List<LQuestions> lQuestionsList = ilQuestionsService.list(queryWrapper);
            for (LQuestions lQuestions: lQuestionsList) {
                LQuestionsType lQuestionsType = ilQuestionsTypeService.getById(lQuestions.getQuestionsType());
                if(null != lQuestionsType)
                    lQuestions.setQuestionsTypeName(lQuestionsType.getQuestionsTypeName());
            }
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lQuestionsList);
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //子分类ID
    private List<Integer> nodeStr (List<Integer> lists){
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LQuestionsSort> queryWrapper = new QueryWrapper<LQuestionsSort>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LQuestionsSort> lQuestionsSorts = ilQuestionsSortService.list(queryWrapper);
            for (int j = 0; j < lQuestionsSorts.size(); j++) {
                LQuestionsSort lQuestionsSort = lQuestionsSorts.get(j);
                ids.add(lQuestionsSort.getQuestionsSortId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }
        ids.addAll(lists);
        return ids;
    }

    //发布
    @ApiOperation(value = "发布考次")
    @GetMapping("/release")
    @UserLoginToken
    @Log(title = "发布考次", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> release(@RequestParam("id")Integer id,@RequestParam(value = "examFile",required = false)String examFile,
                                        @RequestParam(value = "releaseState",required = false)String releaseState,
                                        @RequestParam(value = "releaseTime",required = false)String releaseTime, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            QueryWrapper<LExamPaper> queryWrapper = new QueryWrapper<LExamPaper>();
            queryWrapper.eq("exam_id",id);
            int count = ilExamPaperService.count(queryWrapper);
            if (count<1) {
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_RANDOM_COUNT);
            }
            if (StringUtils.isEmpty(id)) {
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            }
            LExam lExam = new LExam();
            lExam.setExamId(id);
            if(StringUtils.isNotEmpty(examFile))
                lExam.setExamFile(examFile);
            if(StringUtils.isNotEmpty(releaseState))
                lExam.setReleaseState(releaseState);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
            if(null != releaseTime) {
                Date date = simpleDateFormat.parse(releaseTime);
                lExam.setReleaseTime(date);
            }
            lExam.setUpdateTime(new Date());
            lExam.setUpdateUser(userId);
            if(ilExamService.updateById(lExam)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //生成试卷
    @ApiOperation(value = "生成试卷")
    @GetMapping("/setPaper")
    @UserLoginToken
    @Log(title = "生成试卷", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> setPaper(@RequestParam("id")Integer id, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if (StringUtils.isEmpty(id)) {
            return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
        }
        QueryWrapper<LExamPaper> queryWrapper = new QueryWrapper<LExamPaper>();
        queryWrapper.eq("exam_id",id);
        int count = ilExamPaperService.count(queryWrapper);
        LExam lExam = ilExamService.getById(id);
        if(lExam.getRandomSeveral() == count){
            return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_RANDOM);
        }
        ilExamPaperService.examPaper(id,userId);
        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
    }

}
